package com.woniuxy.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yygh.cmn.listener.DistListener;
import com.woniuxy.yygh.cmn.mapper.DictMapper;
import com.woniuxy.yygh.cmn.service.DictService;
import com.woniuxy.yygh.common.result.Result;
import com.woniuxy.yygh.model.cmn.Dict;
import com.woniuxy.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 数据字典实现类
 * <P> Date: 2022/2/27:13:51
 * <P> Description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    /**
     * TODO:根据数据id查询子数据列表
     *      根据当前的父结点的id 就是子结点的parent_id   查找子类
     **/
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {

        //根据当前的父结点的id 就是子结点的parent_id   查找子类
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);

        List<Dict> dicts = baseMapper.selectList(wrapper);

        //向list集合的dict对象设置hasChildren值
        for (Dict dict : dicts) {
            //根据当前id设置每个对象asChildren值
            dict.setHasChildren(isChildren(dict.getId()));
        }
        return dicts;
    }

    /**
     * TODO:导出数据字典接口
     *      设置下载方式 设置返回头信息
     **/
    @Override
    public void exportDistData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            // 设置中文
            response.setCharacterEncoding("utf-8");
            String fileName = "dict";
            //TODO 设置前端下载方式打开 设置头信息
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //TODO 查询dict表 所有数据
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
//            for (Dict dict : dictList) {
//                DictEeVo dictVo = new DictEeVo();
//
//                BeanUtils.copyProperties(dict, dictVo);
//                dictVoList.add(dictVo);
//            }

            dictList.forEach(dict -> {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            });

            //TODO 写入数据
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO: 导入数据字典接口 将查询数据传到redis
     *         allEntries=true 清空缓存
     **/
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {

        //读取excel文件流  转为的对象 插入数据增加 excel表里面的工作区
        try {
            EasyExcel.read(file.getInputStream(),
                            DictEeVo.class,
                            new DistListener(baseMapper))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO: 根据 dictcode 和 value 查询
     *          根据当前所属的字典范围 根据value值来获取对应值
     **/
    @Override
    public String getDictName(String dictCode, String value) {
        //如果 dictcode 为空 只查value

        //dictcode:对应 Hostype 只有医院等级才有

        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();


        } else {

            //根据dict对象查询dict对象 得到dict的id值
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code", dictCode);

            //根据dictcode 获得dict对象的parent_id 对象的id
            Dict codeDice = this.getDictByDictCode(dictCode);

            Long parent_id = codeDice.getParentId();

            System.out.println("父级对象:==" + codeDice);
            System.out.println("parent_id:==" + parent_id);

            //根据 parent_id 和 value进行查询 字典数据
            //父id是查出来的id value就是需要查找的value
            Dict finalDict = baseMapper.selectOne(
                    new QueryWrapper<Dict>()
                            .eq("parent_id", codeDice.getId())
                            .eq("value", value)
            );
            return finalDict.getName();
        }
    }


    /**
     * TODO:根据 ditcode 编码 查询下级节点
     **/
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据ditcode 先获得id
        Dict dict = this.getDictByDictCode(dictCode);

        //获得其下面所有子节点
        List<Dict> childData = this.findChildData(dict.getId());

        return childData;
    }

    @Resource
    private DictMapper dictMapper;

    @Override
    public Result findAll() {

        List<Dict> dicts = dictMapper.findAll();

        return Result.ok(dicts);
    }

    /**
     * TODO: 根据编码获得dict对象
     **/
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDice = baseMapper.selectOne(wrapper);
        return codeDice;
    }

    /**
        * TODO:判断id下面是否有子结点
    **/
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }
}
